package com.ruoyi.flowable.listener;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.flowable.common.constant.ProcessConstants;
import com.ruoyi.flowable.factory.FlowServiceFactory;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.web.servlet.oauth2.client.OAuth2ClientSecurityMarker;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class MultiInstanceCompletionListener implements ExecutionListener {
    FlowServiceFactory flowServiceFactory;


    public MultiInstanceCompletionListener() {
        flowServiceFactory = SpringUtils.getBean("flowServiceFactory");
    }


    @Override
    public void notify(DelegateExecution execution) {
       //子流程变量
        Map<String, Object> subvariables = execution.getVariables();
        subvariables.put("parentProcessInstanceId", execution.getProcessInstanceId());
        //判断子流程是否已经执行完毕

        Object nrOfInstances = execution.getVariables().get("nrOfInstances");
        //循环变量
        Object userIdflagref = flowServiceFactory.getRuntimeService().getVariable(execution.getProcessInstanceId(), "userIdflagref");
        if(nrOfInstances!=null){
        if((int)nrOfInstances>(int)userIdflagref) {
            int temp=(int)flowServiceFactory.getRuntimeService().getVariable(execution.getProcessInstanceId(),"userIdflagref");

            flowServiceFactory.getRuntimeService().setVariable(execution.getProcessInstanceId(), "userIdflagref",temp+1);
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            flowServiceFactory.getIdentityService().setAuthenticatedUserId(sysUser.getUserId().toString());
            subvariables.replace(ProcessConstants.PROCESS_INITIATOR, sysUser.getUserId());
            flowServiceFactory.getRuntimeService().startProcessInstanceById("flow_testsign:29:130004", subvariables);
        }
        }
        else {
            log.info("多实例任务完成");
        }
    }
}
